﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;

namespace RockBus.DataContracts
{
    [DataContract(Namespace = StringConstants.RockBusNamespace)]
    public class PipelineInfo
    {
        private static readonly DataContractSerializer _dcs = new DataContractSerializer(typeof(PipelineInfo));

        public static PipelineInfo CreateFromByteArray(byte[] pipelineInfoByteArray)
        {
            using (var ms = new MemoryStream(pipelineInfoByteArray))
            {
                ms.Position = 0;
                return _dcs.ReadObject(ms) as PipelineInfo;
            }
        }

        private PipelineInfo()
        {
            this.Init();
        }

        public PipelineInfo(string id, params PipelineComponentInfo[] pipelineComponents)
            : this(id, (IEnumerable<PipelineComponentInfo>)pipelineComponents)
        {
        }

        public PipelineInfo(string id, IEnumerable<PipelineComponentInfo> pipelineComponents)
        {
            this.Id = id;
            this.PipelineComponents = new List<PipelineComponentInfo>(pipelineComponents);
        }

        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            this.Init();
        }

        private void Init()
        {
            if (this.PipelineComponents == null)
            {
                this.PipelineComponents = new List<PipelineComponentInfo>();
            }
        }

        [DataMember]
        public string Id { get; set; }

        [DataMember]
        public IEnumerable<PipelineComponentInfo> PipelineComponents { get; set; }

        public byte[] GetByteArray()
        {
            using (var ms = new MemoryStream())
            {
                _dcs.WriteObject(ms, this);
                return ms.ToArray();
            }
        }
    }
}